<template>
  <div>
    <Nav></Nav>
    <div class="container-fluid" style="margin-top: 100px">
      <div class="row">
        <div class="col-md-1"></div>
        <div class="col-md-10">
          <div class="row">
            <div class="col-md-12">
              <div class="card">
                <div class="card-header bg-light text-center">
                  电商平台销售趋势
                </div>
                <div class="card-body">
                  <div class="ibox float-e-margins">
                    <div class="ibox-title">
                      <h5>
                        <span
                          style="font-size: 16px"
                          class="label label-success"
                          >电商平台销售趋势</span
                        >
                      </h5>
                    </div>
                    <div class="ibox-content">
                      <div id="lineChart" style="height: 300px"></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="col-md-1"></div>
      </div>
      <!-- 按钮组 -->
      <div class="row" style="margin-top: 20px">
        <div class="col-md-1"></div>
        <div class="col-md-10">
          <a
            href="#"
            @click="batchDelete()"
            class="btn btn-sm btn-outline-danger"
            ><i class="fa fa-trash-o"></i> 批删除</a
          >
          <a href="/add" class="btn btn-outline-success btn-sm"
            ><i class="fa fa-arrow-up"></i> 添加</a
          >
          <a
            href="#"
            class="btn btn-outline-success btn-sm"
            @click.prevent="exportProduct()"
            ><i class="fa fa-file-excel-o"></i> 导出</a
          >
        </div>
        <div class="col-md-1"></div>
      </div>
      <!-- 看板 -->
      <div class="row">
        <div class="col-md-1"></div>
        <div class="col-md-10">
          <table class="table text-center table-sm table-bordered table-hover">
            <thead>
              <tr class="bg-light text-center">
                <th></th>
                <th><span class="align-self-md-auto">商品名</span></th>
                <th>价格</th>
                <th>库存</th>
                <th>状态</th>
                <th>入库时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="product in productItemList" :key="product.id">
                <td class="text-center">
                  <input
                    type="checkbox"
                    class="item-checkbox"
                    :value="product.id"
                    v-model="selectedProducts"
                  />
                </td>
                <td>{{ product.productName }}</td>
                <td>{{ product.price }}</td>
                <td>{{ product.stock }}</td>
                <td
                  :class="{
                    'badge-success': product.status,
                    'badge-danger': !product.status,
                  }"
                >
                  {{ product.status ? "上架" : "下架" }}
                </td>
                <td>{{ product.launchDate }}</td>
                <td>
                  <a
                    class="btn btn-sm btn-outline-success"
                    href="#"
                    @click.prevent="updateStatus(product.id)"
                  >
                    <i class="fa fa-arrow-up"></i>
                    <span>{{ getStatusText(product.status) }}</span>
                  </a>
                  <a
                    class="btn btn-sm btn-outline-danger"
                    href="#"
                    @click.prevent="deleteProduct(product.id)"
                    ><i class="fa fa-trash-o"></i>删除</a
                  >
                  <a
                    class="btn btn-sm btn-outline-info"
                    href="#"
                    @click.prevent="editProduct(product.id)"
                    ><i class="fa fa-edit"></i>编辑</a
                  >
                  <a
                    class="btn btn-sm btn-outline-info"
                    href="#"
                    @click.prevent="viewProduct(product.id)"
                    ><i class="fa fa-info"></i>查看</a
                  >
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="col-md-1"></div>
      </div>
      <div class="row">
        <div class="col-md-3"></div>
        <div class="col-md-6" style="text-align: center">
      <a class="btn btn-outline-primary" v-if="currentPage > 1" @click="prevPage">上一页</a>
      <a class="btn btn-outline-primary"  @click="nextPage">下一页</a>
        </div>
        <div class="col-md-3"></div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup name="ProductList">
import Nav from "../Nav.vue";
import "../../assets/css/bootstrap.min.css";
import "../../assets/css/font-awesome.css";
import "../../assets/js/echarts.min.js";
import {
  getProductList,
  deleteP,
  exportGoods,
  updateProductStatus,
  deleteBatchProduct,
} from "../../api/product";
import { reactive, onMounted, ref, toRef } from "vue";
import { ElMessage } from "element-plus";
import { useRouter ,useRoute} from "vue-router";
import { saveAs } from "file-saver";
const router = useRouter();
const productItemList = reactive([]);
let selectedProducts = ref([]);
const currentPage = ref(1); 
const totalPage = ref(0);
const batchDelete = async () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.error("请选择要删除的商品");
    return;
  }
  const res = await deleteBatchProduct(selectedProducts.value);
  if (res.data.code === 1) {
    ElMessage.success("批量删除商品成功");
    await getProductItemList();
  }
}

const getProductItemList = async () => {
  const res = await getProductList(currentPage.value);
  if (res.data.code === 1) {
    totalPage.value = res.data.data.pages;
    productItemList.splice(
      0,
      productItemList.length,
      ...res.data.data.productsList
    );
  }
}

const deleteProduct = async (id: number) => {
  const res = await deleteP(id);
  if (res.data.code === 1) {
    ElMessage.success("删除成功");
    await getProductItemList();
  }
}
const viewProduct = async (id: number) => {
  router.push(`/productInfo/${id}`);
};
const editProduct = async (id: number) => {
  router.push(`/productEdit/${id}`);
};
const exportProduct = async () => {
  const res = await exportGoods();
  if (res.status === 200) {
    ElMessage.success("商品导出成功");
    saveAs(res.data, "products.xlsx");
  }
};
const updateStatus = async (id: number) => {
  const res = await updateProductStatus(id);
  if (res.data.code === 1) {
    ElMessage.success("状态更新成功");
    window.location.reload();
  }
};
const getStatusText = (status: any) => {
  return status ? "下架" : "上架";
};
// / 上一页逻辑
const prevPage = async () => {
  if (currentPage.value > 1) {
  const res=  await getProductList(currentPage.value - 1);
   // 更新当前页码
   currentPage.value--;
   productItemList.splice(
      0,
      productItemList.length,
      ...res.data.data.productsList
    );
  }
};
// 下一页逻辑
const nextPage = async () => {
  if (currentPage.value < totalPage.value) {
   const res= await getProductList(currentPage.value +1);
   // 更新当前页码
   currentPage.value++;
   productItemList.splice(
      0,
      productItemList.length,
      ...res.data.data.productsList
    );
  }
};

function getData() {
  var myChart = echarts.init(document.getElementById("lineChart"));
  // 发起fetch请求获取数据
  fetch("/api/echart/data")
    .then((response) => {
      if (!response.ok) throw new Error("");
      return response.json();
    })
    .then((data) => {
      var option = {
        title: {
          text: "",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            label: {
              backgroundColor: "#6a7985",
            },
          },
        },
        legend: {
          data: ["销售量", "访问量"],
        },
        toolbox: {},
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            boundaryGap: false,
            name: "/月份", // 添加单位
            // data: data.months
            data: data[0],
          },
        ],
        yAxis: [
          {
            type: "value",
            axisLabel: {
              formatter: "{value} 次",
            },
          },
        ],
        series: [
          {
            name: "销售量",
            type: "line",
            stack: "总量",
            areaStyle: {},
            data: data[1],
            // data: data.sales
          },
          {
            name: "访问量",
            type: "line",
            stack: "总量",
            label: {
              normal: {
                show: true,
                position: "top",
              },
            },
            areaStyle: {},
            data: data[2],
            // data: data.visits
          },
        ],
      };
      myChart.setOption(option);
    });
}
onMounted(() => {
  getProductItemList(), getData();
});
</script>

<style scoped>
.table td {
  vertical-align: middle;
}
</style>
